# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     seg_every_char
   Description :
   Author :       'li'
   date：          2018/11/4
-------------------------------------------------
   Change Activity:
                   2018/11/4:
-------------------------------------------------
"""
import cv2
import numpy as np


def load_img_to_gray(img):
    """
    转变成灰度图片
    :param img:
    :return:
    """
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

def to_gray(img):
    """
    转变成灰度图片
    :param img:
    :return:
    """
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

def append_text_area(text_array, current_array):
    """
    add and filter text area
    :param text_array:
    :param current_array:
    :return:
    """
    if len(current_array) > 3:
        text_array.append(current_array)


def get_text_array(local):
    text_array = []
    current_array = []
    for lo in local[0]:
        if len(current_array) == 0 or current_array[-1] + 1 == lo:
            current_array.append(lo)
        else:
            append_text_area(text_array, current_array)
            current_array = [lo]
    if len(current_array) > 0:
        append_text_area(text_array, current_array)
    print(text_array)
    return text_array


def get_horizontal_seg_array(gray_img):
    """
    get horizontal text area,including 11 box num.
    :param gray_img:
    :return:
    """
    shape = gray_img.shape
    value = np.var(gray_img, axis=0)
    ave_value = np.sum(value) / shape[1]
    per_value = value / ave_value
    is_text = (per_value > 0.5)
    local = np.where(is_text == True)
    text_array = get_text_array(local)
    return text_array

def get_vertical_seg_array(gray_img):
    """
    get horizontal text area,including 11 box num.
    :param gray_img:
    :return:
    """
    shape = gray_img.shape
    value = np.var(gray_img, axis=1)
    ave_value = np.sum(value) / shape[0]
    per_value = value / ave_value
    is_text = (per_value > 0.5)
    local = np.where(is_text == True)
    print(local[0])
    text_array = get_text_array(local)
    return text_array


def seg_vertical(label, img):
    gray_img = to_gray(img)
    text_array = get_vertical_seg_array(gray_img)
    for index, area in enumerate(text_array):
        tmp_img = gray_img[area[0]:area[-1], :]
        cv2.imwrite('seg' + str(index) + '.jpg', tmp_img)
    pass


def main():
    path = '3.jpg'
    label = 'MSCU'
    img = cv2.imread(path)
    seg_vertical(label, img)


if __name__ == '__main__':
    main()
